package com.ruoyi.common.utils.tree;

import com.alibaba.fastjson2.JSONObject;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

public class TreeDataUtils {

	private volatile static TreeDataUtils INSTANCE;

    // 构造方法私有化
    private TreeDataUtils() {

    }

    // 获取树工具单例 （DCL单例）
    public static TreeDataUtils getInstance() {
        if (INSTANCE == null) {
            synchronized (TreeDataUtils.class) {
                if (INSTANCE == null) {
                    INSTANCE = new TreeDataUtils();
                }
            }
        }
        return INSTANCE;
    }

    public <T extends TreeItem> List<T> enquireTree(List<T> treeItemList, String pidName) {

        if (treeItemList.isEmpty()) {
            return null;
        }

        // 过滤空对象
        List<T> treeItems = treeItemList.stream().filter(treeItem -> treeItem != null).collect(Collectors.toList());

        // 存储 id treeItem
        HashMap<String, T> itemMap = new HashMap<>();
        treeItems.forEach(treeItem -> {
            itemMap.put(treeItem.getId(), treeItem);
        });

        List<T> result = new ArrayList<T>();
        // 声明一个变量存放根节点
        T root = null;

        // 数据组装
        for (T treeItem : treeItems) {
            String pid = treeItem.getParentId();
            if (pid.equals(pidName)) {
                // 说明该节点为根节点
                root = treeItem;
                result.add(root);
                continue;
            }
            TreeItem parent = itemMap.get(pid);
            parent.getChildren().add(treeItem);
        }
        return result;
    }

    
    public static void main(String[] args) {

        List<TreeItem> treeItemList = Arrays.asList(
            new TreeItem("1", "0", "中国"),
            new TreeItem("10", "1", "河北"),

            new TreeItem("1221", "0", "美国"),
            new TreeItem("100", "10", "北京"),
            new TreeItem("110", "10", "天津"),
            new TreeItem("20", "1", "河南"),
            new TreeItem("200", "20", "郑州"),
            new TreeItem("210", "20", "洛阳"),
            new TreeItem("220", "20", "许昌"),
            new TreeItem("1220", "1221", "加州"),
            new TreeItem("1223", "1221", "弗洛里达州")
        );

        List<TreeItem> treeItem = TreeDataUtils.getInstance().enquireTree(treeItemList,"0");

        System.out.println(JSONObject.toJSONString(treeItem));

    }
}
